package com.xh.bussiness.xkw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.xh.bussiness.log.model.BizQuestionLog;
import com.xh.bussiness.log.service.IBizQuestionLogService;
import com.xh.bussiness.system.model.Area;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.IAreaService;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.model.*;
import com.xh.bussiness.tiku.service.*;
import com.xh.bussiness.tiku.util.QuestionConverUtils;
import com.xh.bussiness.xkw.bean.request.QuestionSearchRequest;
import com.xh.bussiness.xkw.constant.XkwAPIURL;
import com.xh.bussiness.xkw.constant.XkwCacheConstant;
import com.xh.bussiness.xkw.dao.*;
import com.xh.bussiness.xkw.model.*;

import com.xh.bussiness.xkw.service.IXkwQuestionLogService;
import com.xh.bussiness.xkw.service.IXkwQuestionService;
import com.xh.bussiness.xkw.service.IXkwSubjectService;
import com.xh.bussiness.xkw.utils.ConfigUtils;
import com.xh.bussiness.xkw.utils.XkwHttpsUtils;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class XkwQuestionServiceImpl extends BaseServiceImpl<XkwQuestionMapper, XkwQuestion> implements IXkwQuestionService {

    public static final Logger log = LoggerFactory.getLogger(XkwQuestionServiceImpl.class);

    @Autowired
    private IXkwQuestionLogService xkwQuestionLogService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IPaperService paperService;
    @Autowired
    private IBizQuestionLogService bizQuestionLogService;


    private final String XkwApiSeriveUrl;

    @Autowired
    public XkwQuestionServiceImpl(ConfigUtils configUtils) {
        XkwApiSeriveUrl = configUtils.getXkwApiSeriveUrl();
    }

    /**
     * 查询题目，通过学科网返回的openId和试卷Id
     *
     * @param openid  用户openId
     * @param paperid 试卷Id
     */
    @Override
    public Integer getXkwData(String requestId, String businessType, String openid, String paperid) {
        String getXKWQuestionURL = XkwApiSeriveUrl + XkwAPIURL.GET_PAPER_DESC;
        String url = String.format(getXKWQuestionURL, openid, paperid);
        String str = XkwHttpsUtils.doGet(url);
       /* String str = null;
        try {
            str = Files.asCharSource(new File("C:\\Users\\13716\\Desktop\\data.txt"), Charsets.UTF_8).read();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        System.out.println(str);
        Map map = JSONObject.parseObject(str, Map.class);
        Integer bankId = Integer.valueOf(map.get("bankId") == null ? "0" : map.get("bankId").toString());
        Object head = map.get("head");
        Object body = map.get("body");
        //返回 List<XkwQuestion> 集合对象
        List<XkwQuestion> list = fomatBody(requestId, businessType, body.toString(), bankId);

        //返回 List<Map> 集合对象
//        List<Map> list = fomatBody2(requestId, body.toString(), bankId);
        return list.size();
    }

    /**
     * 格式化从学科网返回的json数据
     *
     * @param body json数据
     */
    private List<XkwQuestion> fomatBody(String requestId, String businessType, String body, Integer subjectId) {
        //格式化body
        List<Map> bodyJson = (List<Map>) JSONArray.parse(body);

        List<XkwQuestion> datas = new ArrayList<>();
        for (Map bodyMap : bodyJson) {
            //Map partHead = (Map) bodyMap.get("partHead");
            Object partBody = bodyMap.get("partBody");
            List<Map> partJson = (List<Map>) JSONArray.parse(partBody.toString());
            for (Map partMap : partJson) {
                Object questionsJson = partMap.get("questions");
                List<XkwQuestion> xkwQuestions = formatQuestion(questionsJson.toString(), subjectId);

                datas.addAll(xkwQuestions);
            }
        }
        //处理业务
        doBusiness(requestId, businessType, datas);
        return datas;
    }

    private List<XkwQuestion> formatQuestion(String questionsJson, Integer subjectId) {
        //主要属性整合
        List<XkwQuestion> questionList = new ArrayList<>();

        List<Map> questions = (List<Map>) JSONArray.parse(questionsJson);
        for (Map question : questions) {
            //试题题干
//            String quesBody = question.get("quesBody").toString().replaceAll("<img src=\"Upload","<img src=\"https://staticzujuan.xkw.com/quesimg/Upload");
            String quesBody = question.get("quesBody").toString();
            quesBody = quesBody.replaceAll("<img src=\\\"Upload", "<img src=\"https://staticzujuan.xkw.com/quesimg/Upload");
            quesBody = quesBody.replaceAll("<img src=\"Upload", "<img src=\"https://staticzujuan.xkw.com/quesimg/Upload");
            org.jsoup.nodes.Document document = Jsoup.parseBodyFragment(quesBody);

            Elements elements = document.select("img[src]");
            for(Element element :elements){
                if(!element.attr("src").contains("http")){
                    quesBody = extractImgUrl(quesBody);
                }
            }
            if(quesBody.contains("<html>")){
                org.jsoup.nodes.Document doc = Jsoup.parseBodyFragment(quesBody);
                quesBody = doc.body().children().toString();
            }
            System.out.println(quesBody);
            //地区 List<Map>
            Object areasObj = question.get("areas");
            List<Map> areas = (List<Map>) JSONArray.parse(areasObj.toString());

            //更新时间
            Object auditTimeObj = question.get("auditTime");
//            LocalDateTime auditTime = str2LocalDateTime(auditTimeObj.toString());
            LocalDateTime auditTime = null;
            if (auditTimeObj != null) {
                auditTime = str2LocalDateTime(auditTimeObj.toString());
            }


            //知识点
            Object categoriesObj = question.get("categories");
            List<List<Map>> categories = (List<List<Map>>) JSONArray.parse(categoriesObj.toString());
            //章节
            Object chaptersObj = question.get("chapters");
            List<List<Map>> chapters = (List<List<Map>>) JSONArray.parse(chaptersObj.toString());
            //拆分后的小题列表
            Object childQuesObj = question.get("childQues");
            List<Map> childQues = (List<Map>) JSONArray.parse(childQuesObj.toString());
            //学段
            Object gradesObj = question.get("grades");
            List<Map> grades = (List<Map>) JSONArray.parse(gradesObj.toString());

            //试题id
            Integer id = Integer.valueOf(question.get("id").toString());
            //试题知识点  数据为空
            String knowledge = question.get("knowledge").toString();

            //拆分的选项
            Object optionsObj = question.get("options");
            List<Map> options = (List<Map>) JSONArray.parse(optionsObj.toString());
            //试卷类型
            Object paperTypesObj = question.get("paperTypes");
            List<Map> paperTypes = (List<Map>) JSONArray.parse(paperTypesObj.toString());
            //试题平台id
            String qbmId = question.get("qbmId").toString();
            //试题答案
            String quesAnswer = question.get("quesAnswer").toString().replaceAll("<img src=\"Upload", "<img src=\"https://staticzujuan.xkw.com/quesimg/Upload");
            //试题属性
            Object quesAttributeObj = question.get("quesAttribute");
            Map quesAttribute = null;
            if (Objects.nonNull(quesAttributeObj)) {
                quesAttribute = JSONObject.parseObject(quesAttributeObj.toString(), Map.class);
            }
            //包含小题数
            Integer quesChildNum = Integer.valueOf(question.get("quesChildNum").toString());
            //试题难度
            Object quesDiffObj = question.get("quesDiff");
//            Map quesDiff = JSONObject.parseObject(quesDiffObj.toString(), Map.class);
            Map quesDiff = new HashMap();
            if(quesDiffObj!=null){
                quesDiff = JSONObject.parseObject(quesDiffObj.toString(), Map.class);
            }

            //试题难度值
//            BigDecimal quesDiffValue = BigDecimal.valueOf(Double.valueOf(question.get("quesDiffValue").toString()));
            String quesDiffValueStr = question.get("quesDiffValue").toString();
            BigDecimal quesDiffValue = null;
            if(StringUtils.isNotEmpty(quesDiffValueStr)){
                quesDiffValue = new BigDecimal(Double.valueOf(quesDiffValueStr));
            }
            //试题Guid
            String quesGuid = question.get("quesGuid").toString();
            //试题解析
            String quesParse = question.get("quesParse").toString().replaceAll("<img src=\"Upload", "<img src=\"https://staticzujuan.xkw.com/quesimg/Upload");
            //试题分数
            Integer quesScore = Integer.valueOf(question.get("quesScore").toString());
            //试题星级
            Integer quesStar = Integer.valueOf(question.get("quesStar").toString());
            //试题类型
            Object quesTypeObj = question.get("quesType");
            Map quesType = null;
            if (quesTypeObj != null) {
                quesType = JSONObject.parseObject(quesTypeObj.toString(), Map.class);
            }
            //添加日期
            Object timeObj = question.get("time");
//            LocalDateTime time = str2LocalDateTime(timeObj.toString());
            LocalDateTime time = null;
            if(timeObj!=null){
                time = str2LocalDateTime(timeObj.toString());
            }
            //试题名称

            String title = question.get("title").toString();
            //使用次数
            Integer useSum = Integer.valueOf(question.get("useSum").toString());
            //试题来源
            String from = question.get("from").toString();


            if (null == subjectId) {
                subjectId = Integer.valueOf(question.get("bankId").toString());
            }

            XkwQuestion xkwQuestion = new XkwQuestion();
            xkwQuestion.setSubjectId(subjectId);
            xkwQuestion.setQuesBody(quesBody);
            xkwQuestion.setOptions(formatMap2Prorperty(options));
            xkwQuestion.setQuesAnswer(quesAnswer);
            xkwQuestion.setQuesParse(quesParse);
            xkwQuestion.setAuditTime(auditTime);
            xkwQuestion.setFrom(from);
            xkwQuestion.setXkwId(id);
            xkwQuestion.setKnowledge(knowledge);
            xkwQuestion.setPaperTypes(formatMap2Prorperty(paperTypes));
            xkwQuestion.setQbmId(qbmId);
            xkwQuestion.setQuesDiffValue(quesDiffValue);
            xkwQuestion.setQuesGuid(quesGuid);
            xkwQuestion.setQuesChildNum(quesChildNum);
            xkwQuestion.setQuesDiff(getPropertyPriority(quesDiff));
            if (quesAttribute != null) {
                xkwQuestion.setQuesAttribute(getPropertyPriority(quesAttribute));
            }
            xkwQuestion.setQuesScore(quesScore);
            xkwQuestion.setTime(time);
            xkwQuestion.setQuesStar(quesStar);
            xkwQuestion.setTitle(title);
            xkwQuestion.setUseSum(useSum);
            xkwQuestion.setGrades(grades);
            xkwQuestion.setAreas(formatMap2Prorperty(areas));
            //添加知识点
            List<List<PropertyPriority>> categoryList = new ArrayList<>();
            categories.forEach(item -> {
                categoryList.add(formatMap2Prorperty(item));
            });
            xkwQuestion.setCategories(categoryList);
            //添加章节
            List<List<PropertyPriority>> chapterList = new ArrayList<>();
            chapters.forEach(item -> {
                chapterList.add(formatMap2Prorperty(item));
            });
            xkwQuestion.setChapters(chapterList);
            xkwQuestion.setGrades(grades);
            xkwQuestion.setQuesType(quesType);

            questionList.add(xkwQuestion);
        }

        return questionList;
    }


    //业务操作
    public void doBusiness(String requestId, String businessType, List<XkwQuestion> xkwQuestions) {
        List<String> questionIds = saveXkwQuestion(xkwQuestions);
        if (CollectionUtils.isEmpty(questionIds)) {
            return;
        }
        switch (businessType) {
            case XkwCacheConstant.BizType.PAPER:
            case XkwCacheConstant.BizType.ENTRANCETEST:
                paperService.addPaperQuestion(businessType,requestId, questionIds);
                break;
            case XkwCacheConstant.BizType.KNOWLEDGE:
            case XkwCacheConstant.BizType.HANDOUT:
                BizQuestionLog importLog = new BizQuestionLog();
                int type = XkwCacheConstant.BizType.KNOWLEDGE.equals(businessType) ? 1 : 2;
                importLog.setType(type);
                importLog.setRelationId(requestId);
                String ids = String.join(",", questionIds);
                importLog.setQuestionIds(ids);
                bizQuestionLogService.insert(importLog);
                break;
            default:
                log.error("No business by businessType:" + businessType);
                break;
        }
        CacheUtils.set(String.format("%s_%s_%s", XkwCacheConstant.CALL_BACK, businessType, requestId), questionIds.size(), 60 * 60 * 24);
    }


    private List<Map> fomatBody2(String requestId, String body, Integer subjectId) {
        List<Map> result = new ArrayList<>();
        //xkw  id集合
        StringBuilder xkwQid = new StringBuilder();
        //格式化body
        List<Map> bodyJson = (List<Map>) JSONArray.parse(body);
        for (Map bodyMap : bodyJson) {
            Map partHead = (Map) bodyMap.get("partHead");

            Object partBody = bodyMap.get("partBody");
            List<Map> partJson = (List<Map>) JSONArray.parse(partBody.toString());
            for (Map partMap : partJson) {
                Map type = (Map) partMap.get("type");

                Object questionsJson = partMap.get("questions");
                List<Map> questions = formatQuestion2(requestId, questionsJson.toString(), subjectId);
                result.addAll(questions);
            }
        }
        if (result.size() > 0) {
            result.forEach(map -> {
                xkwQid.append(map.get("xkwId")).append(",");
            });

            saveXkwIdLog(requestId, xkwQid.toString());
        }
        return result;
    }

    private List<Map> formatQuestion2(String requestId, String questionsJson, Integer subjectId) {
        //主要整合
        List<Map> questionList = new ArrayList<>();


        List<Map> questions = (List<Map>) JSONArray.parse(questionsJson);
        for (Map question : questions) {

            //试题题干
            String quesBody = question.get("quesBody").toString();

            //地区 List<Map>
            Object areasObj = question.get("areas");
            List<Map> areas = (List<Map>) JSONArray.parse(areasObj.toString());

            //更新时间
            Object auditTimeObj = question.get("auditTime");
            LocalDateTime auditTime = str2LocalDateTime(auditTimeObj.toString());

            //知识点
            Object categoriesObj = question.get("categories");
            List<List<Map>> categories = (List<List<Map>>) JSONArray.parse(categoriesObj.toString());
            //章节
            Object chaptersObj = question.get("chapters");
            List<List<Map>> chapters = (List<List<Map>>) JSONArray.parse(chaptersObj.toString());
            //拆分后的小题列表
            Object childQuesObj = question.get("childQues");
            List<Map> childQues = (List<Map>) JSONArray.parse(childQuesObj.toString());
            //学段
            Object gradesObj = question.get("grades");
            List<Map> grades = (List<Map>) JSONArray.parse(gradesObj.toString());

            //试题id
            Integer id = Integer.valueOf(question.get("id").toString());
            //试题知识点  数据为空
            String knowledge = question.get("knowledge").toString();

            //拆分的选项
            Object optionsObj = question.get("options");
            List<Map> options = (List<Map>) JSONArray.parse(optionsObj.toString());
            //试卷类型
            Object paperTypesObj = question.get("paperTypes");
            List<Map> paperTypes = (List<Map>) JSONArray.parse(paperTypesObj.toString());
            //试题平台id
            String qbmId = question.get("qbmId").toString();
            //试题答案
            String quesAnswer = question.get("quesAnswer").toString();
            //试题属性
            Object quesAttributeObj = question.get("quesAttribute");
            Map quesAttribute = JSONObject.parseObject(null == quesAttributeObj ? null : quesAttributeObj.toString(), Map.class);
            //包含小题数
            Integer quesChildNum = Integer.valueOf(question.get("quesChildNum").toString());
            //试题难度
            Object quesDiffObj = question.get("quesDiff");
            Map quesDiff = JSONObject.parseObject(quesDiffObj.toString(), Map.class);
            //试题难度值
            BigDecimal quesDiffValue = BigDecimal.valueOf(Double.valueOf(question.get("quesDiffValue").toString()));
            //试题Guid
            String quesGuid = question.get("quesGuid").toString();
            //试题解析
            String quesParse = question.get("quesParse").toString();
            //试题分数
            Integer quesScore = Integer.valueOf(question.get("quesScore").toString());
            //试题星级
            Integer quesStar = Integer.valueOf(question.get("quesStar").toString());
            //试题类型
            Object quesTypeObj = question.get("quesType");
            Map quesType = JSONObject.parseObject(quesTypeObj.toString(), Map.class);
            Integer questionType = Integer.valueOf(quesType.get("id").toString());
            //添加日期
            Object timeObj = question.get("time");
            LocalDateTime time = str2LocalDateTime(timeObj.toString());
            //试题名称
            String title = question.get("title").toString();
            //使用次数
            Integer useSum = Integer.valueOf(question.get("useSum").toString());
            //试题来源
            String from = question.get("from").toString();

            if (null == subjectId) {
                subjectId = Integer.valueOf(question.get("bankId").toString());
            }

            Map<String, Object> questionInfo = new HashMap<>();
            questionInfo.put("subjectId", subjectId);
            questionInfo.put("xkwId", id);
            questionInfo.put("name", quesBody);
            questionInfo.put("answer", quesAnswer);
            questionInfo.put("questions", childQues);
            questionInfo.put("jx", quesParse);
            questionInfo.put("type", questionType);
            //来源
            questionInfo.put("from", "xkw");

            questionList.add(questionInfo);
        }

//        saveXkwQuestion(questionList);

        return questionList;
    }

    private void saveXkwIdLog(String id, String xkwIds) {

        XkwQuestionLog xkwQuestionLog = new XkwQuestionLog();
        xkwQuestionLog.setRequestId(id);
        xkwQuestionLog.setXkwQid(xkwIds);
        try {
            xkwQuestionLogService.insert(xkwQuestionLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<String> saveXkwQuestion(List<XkwQuestion> questionList) {
        List<String> questionIds = new ArrayList<>();
        for (XkwQuestion question : questionList) {
            System.out.println(JSON.toJSON(question));
            // 将学科网试题转化为本系统里的试题
            QuestionDto questionDto = QuestionConverUtils.xkwQuestion2MyQuestion(question);

            questionDto = questionService.addQuestion(questionDto);
            questionIds.add(questionDto.getId());

            question.setQuestionId(questionDto.getId());
        }
        // TODO: 保存成试卷
        return questionIds;
    }

    /**
     * 格式化 list<map> 类型的数据  转换为 List<PropertyPriority>类型
     *
     * @param props 参数
     * @return
     */
    public List<PropertyPriority> formatMap2Prorperty(List<Map> props) {
        List<PropertyPriority> properties = new ArrayList<>();
        if (!props.isEmpty()) {
            props.forEach(map -> {
                PropertyPriority propertyPriority = getPropertyPriority(map);
                properties.add(propertyPriority);
            });

        }
        return properties;
    }

    private PropertyPriority getPropertyPriority(Map map) {
        if (!map.isEmpty()) {
            Integer id = Integer.valueOf(map.get("id").toString());
            String name = map.get("name").toString();
            PropertyPriority propertyPriority = new PropertyPriority(id, name);
            return propertyPriority;
        }
        return null;
    }

    public LocalDateTime str2LocalDateTime(String dateTime) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(dateTime, dtf);
        return parse;
    }

    @Override
    public List<QuestionDto> queryQuestionByImg(String base64ImgStr) {
        String url = XkwApiSeriveUrl + XkwAPIURL.QUERY_QUESTIONS_PHOTO_SEARCH;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imgStr", base64ImgStr);
        jsonObject.put("pattern", 2);
        String xkwQuestionStr = XkwHttpsUtils.doPost(url, jsonObject);
        if (null == xkwQuestionStr) {
            return new ArrayList<>();
        }
        System.out.println(xkwQuestionStr);
        List<QuestionDto> dtos = new ArrayList<>();
        List<XkwQuestion> xkwQuestions = formatQuestion(xkwQuestionStr, null);
        if (!CollectionUtils.isEmpty(xkwQuestions)) {
            for (XkwQuestion xkwQuestion : xkwQuestions) {
                System.out.println(xkwQuestion.getQuesBody());
                QuestionDto questionDto = QuestionConverUtils.xkwQuestion2MyQuestion(xkwQuestion);
                if (questionDto != null) {
                    dtos.add(questionDto);
                }
            }
        }
        return dtos;
    }

    @Override
    public List<QuestionDto> queryQuestionRandom(QuestionSearchRequest request) {
        String queryUrl = String.format(XkwAPIURL.QUERY_QUESTIONS_RANDOM, request.getBankId());
        String requestParam = null;
        try {
            requestParam = createRequestParam(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = XkwApiSeriveUrl + queryUrl + requestParam;

        String xkwQuestionStr = XkwHttpsUtils.doGet(url);
        if (null == xkwQuestionStr) {
            return new ArrayList<>();
        }
        System.out.println(xkwQuestionStr);
        List<QuestionDto> dtos = new ArrayList<>();
        List<XkwQuestion> xkwQuestions = formatQuestion(xkwQuestionStr, request.getBankId());
        if (!CollectionUtils.isEmpty(xkwQuestions)) {
            for (XkwQuestion xkwQuestion : xkwQuestions) {
                System.out.println(xkwQuestion.getQuesBody());
                QuestionDto questionDto = QuestionConverUtils.xkwQuestion2MyQuestion(xkwQuestion);
                if (StringUtils.isNotEmpty(questionDto.getTitle())) {
                    dtos.add(questionDto);
                }
            }
        }
        return dtos;
    }

    @Override
    public List<QuestionDto> queryQuestionByKeyword(QuestionSearchRequest request) {
        String queryUrl = String.format(XkwAPIURL.QUERY_QUESTIONS_SEARCH, request.getBankId());
        String requestParam = null;
        try {
            requestParam = createRequestParam(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = XkwApiSeriveUrl + queryUrl + requestParam;

        String xkwQuestionStr = XkwHttpsUtils.doGet(url);
        if (null == xkwQuestionStr) {
            return new ArrayList<>();
        }
        System.out.println(xkwQuestionStr);
        List<QuestionDto> dtos = new ArrayList<>();
        List<XkwQuestion> xkwQuestions = formatQuestion(xkwQuestionStr, request.getBankId());
        if (!CollectionUtils.isEmpty(xkwQuestions)) {
            for (XkwQuestion xkwQuestion : xkwQuestions) {
                System.out.println(xkwQuestion.getQuesBody());
                QuestionDto questionDto = QuestionConverUtils.xkwQuestion2MyQuestion(xkwQuestion);
                if (StringUtils.isNotEmpty(questionDto.getTitle())) {
                    dtos.add(questionDto);
                }
            }
        }
        return dtos;
    }

    @Override
    public List<Map> queryQuestion(String uuid) throws Exception {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("logId", uuid);
        queryWrapper.orderByDesc("createTime");

        List<XkwQuestionLog> logs = xkwQuestionLogService.queryByCondition(queryWrapper);
        if (logs.isEmpty()) {
            return new ArrayList<>();
        }
        //取最新的一条数据
        XkwQuestionLog xkwQuestionLog = logs.get(0);
        String xkwQid = xkwQuestionLog.getXkwQid();
        long[] ids = Arrays.stream(xkwQid.split(",")).mapToLong(Long::valueOf).toArray();

        queryWrapper = new QueryWrapper();
        queryWrapper.in("xkwId", ids);
        List list = super.queryByCondition(queryWrapper);
        return list;
    }

//    public void initQuestionType() throws Exception {
//
//        List<Map> subjectLists = dao.queryAll(new Query(), "sys.subject");
//        for (Map subjectMap : subjectLists) {
//
//            Map<String,Object> result = new HashMap<>();
//
//            Integer subjectId = Integer.valueOf(subjectMap.get("id").toString());
//
//            List<Integer> xkwSubjectIds = (List<Integer>) JSONArray.parse(subjectMap.get("xkwSubject").toString());
//            Criteria criteria = Criteria.where("xkwSubjectId").in(xkwSubjectIds);
//            List<XkwQuesType> xkwQuesTypes = dao.queryAll(new Query(criteria), XkwQuesType.class);
//            if(xkwQuesTypes.size() > 0){
//                Map<String, List<XkwQuesType>> collect = xkwQuesTypes.stream().collect(Collectors.groupingBy(XkwQuesType::getName));
//                collect.forEach((k,v)->{
//                    List<Integer> xkwIds = v.stream().map(XkwQuesType::getXkwId).collect(Collectors.toList());
//                    result.put("subjectId",subjectId);
//                    result.put("name",k);
//                    result.put("xkwTypeIds",xkwIds);
//
//                    try {
//                        dao.insert(result,"sys.xkw.ques.type.relation");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                });
//            }
//
//        }
//
//    }

    /**
     * 抽取图片链接
     * @author 赵文博
     * @date 2021/6/1 17:32
     * @param htmlStr
     * @return java.lang.String
     **/
    private String extractImgUrl(String htmlStr) {
        Set<String> pics = new HashSet<String>();
        String img;
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return "<img src='"+pics.toString().substring(1, pics.toString().length() - 1)+"'/>";
    }

    private String createRequestParam(QuestionSearchRequest request) throws Exception {
        StringJoiner joiner = new StringJoiner("&","?","");

        if(StringUtils.isNotEmpty(request.getSearchKeyword())) {
            joiner.add("searchKeyword="+ URLEncoder.encode(request.getSearchKeyword(),"UTF-8"));
        }
        if(null != request.getHighlight()){
            joiner.add("highlight="+ request.getHighlight());
        }
        if(null != request.getPageIndex()){
            joiner.add("pageIndex="+ request.getPageIndex());
        }
        if(null != request.getLearnGrades()){
            joiner.add("learnGrades="+ request.getLearnGrades());
        }
        if(null != request.getPageSize()){
            joiner.add("pageSize="+ request.getPageSize());
        }
        if(null != request.getProvince()){
            joiner.add("province="+ request.getProvince());
        }
        if(null != request.getQuesDiff()){
            joiner.add("quesDiff="+ request.getQuesDiff());
        }
        if(null != request.getQuesType()){
            joiner.add("quesType="+ request.getQuesType());
        }
        if(null != request.getYear()){
            joiner.add("year="+ request.getYear());
        }
        if(null != request.getCategoryId()){
            joiner.add("categoryId="+ request.getCategoryId());
        }
        if(null != request.getIsSynchQues()){
            joiner.add("isSynchQues="+ request.getIsSynchQues());
        }
        if(null != request.getPaperLevel()){
            joiner.add("paperLevel="+ request.getPaperLevel());
        }
        if(null != request.getPaperType()){
            joiner.add("paperType="+ request.getPaperType());
        }
        if(StringUtils.isNotEmpty(request.getQuesStars())) {
            joiner.add("quesStars="+ URLEncoder.encode(request.getQuesStars(),"UTF-8"));
        }
        return joiner.toString();
    }
}
